package com.kiku.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kiku.reggie.common.R;
import com.kiku.reggie.dto.DishDto;
import com.kiku.reggie.entity.Category;
import com.kiku.reggie.entity.Dish;
import com.kiku.reggie.entity.DishFlavor;
import com.kiku.reggie.service.CategoryService;
import com.kiku.reggie.service.DishFlavorService;
import com.kiku.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @className: DishController
 * @description: TODO 类描述
 * @author: kiku
 * @date: 2023/10/21 21:37
 **/
@RestController
@RequestMapping("/dish")
@Slf4j
//菜品管理
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    //
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }


    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造一个分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //构造一个条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //进行分页查询
        dishService.page(pageInfo, queryWrapper);
        //进行对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            //进行对象的拷贝
            BeanUtils.copyProperties(record, dishDto);
            Long categoryId = record.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            //拿到分类名
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            dishDtos.add(dishDto);

        }
        dishDtoPage.setRecords(dishDtos);
        return R.success(dishDtoPage);

    }


    //根据id查询菜品信息和口味信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){

        DishDto dishdto = dishService.getByIdWithFlavor(id);
        return R.success(dishdto);

    }

    //进行菜品的修改
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);
//        //清理所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");
        //清理某个分类下的菜品缓存
        String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();

        redisTemplate.delete(key);

        return R.success("新增菜品成功");
    }

//    //根据条件查询对应的菜品数据
//    @GetMapping("/list")
//    public  R<List<Dish>> list(Dish dish){
//
//        //构造查询条件
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        //查询状态是启售的
//        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }

    //根据条件查询对应的菜品数据
    @GetMapping("/list")

    public  R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtos=null;
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //先从redis中获取缓存数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos!=null){
            //如果存在，则直接返回，无需查询数据库
            return R.success(dishDtos);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //查询状态是启售的
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

         dishDtos = new ArrayList<>();
        for (Dish record : list) {
            DishDto dishDto = new DishDto();
            //进行对象的拷贝
            BeanUtils.copyProperties(record, dishDto);
            Long categoryId = record.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            //拿到分类名
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            //当前菜品的id
            Long dishId = record.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            dishDtos.add(dishDto);
        }
        //如果不存在，就先进行数据库的查询，后将查到的菜品数据缓存
        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);

        return R.success(dishDtos);
    }
}
